package com.example.demo.utils

import com.example.demo.service.sso.UserResource

//suspend fun yieldUserResource(resource: List<UserResource>):Sequence<UserResource>{
//     for (item in resource){
//         return if(item.children.isEmpty()){
//             sequence {
//                 yield(item)
//             }
//         }else{
//             yieldUserResource(item.children)
//         }
//     }
//    return sequence {  }
//}

fun List<UserResource>.toOneResources(arrayList: ArrayList<UserResource>){
    for(item in this){
        if(item.children == null || item.children.isEmpty()){
            arrayList.add(item)
        }else{
            ArrayList(item.children).toOneResources(arrayList)
            val newItem = item.copy()
            newItem.children = ArrayList()
            arrayList.add(newItem)
        }
    }
}

fun List<UserResource>.toTree():List<UserResource>{
    val resourceMap = this.map { it.id to it }.toMap()
    val root = ArrayList<UserResource>()
    for(item in this){
        val parentId = item.id.substring(2)
        val parent = resourceMap[parentId]
        if(parent == null){
            root.add(item)
        }else{
            parent.children.add(item)
        }
    }
    return root
}